import { _decorator, Component, Node, Label, EditBox, Sprite } from "cc";
import { BaseComponent } from "../../core/component/BaseComponent";
import { Engine } from "../../core/Engine";
import { getNumFloor } from "../../core/utils/utils";
import { EVENT_NAME } from "../GameConstant";
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = DipatchSoldierItem
 * DateTime = Sun Jan 09 2022 23:02:33 GMT+0800 (中国标准时间)
 * Author = han2007happy
 * FileBasename = DipatchSoldierItem.ts
 * FileBasenameNoExtension = DipatchSoldierItem
 * URL = db://assets/scripts/game/map/DipatchSoldierItem.ts
 * ManualUrl = https://docs.cocos.com/creator/3.3/manual/en/
 *
 */

@ccclass("DispatchSoldierItem")
export class DispatchSoldierItem extends BaseComponent {
    @property({ type: Label, displayName: "名称" })
    soldierNameLab!: Label;

    @property({ type: Sprite, displayName: "资源图" })
    soldierIcon!: Sprite;

    @property({ type: Label, displayName: "兵总数" })
    soldierNum!: Label;

    @property({ type: EditBox, displayName: "出兵数" })
    soldierDispatchInput!: EditBox;

    isQuickCheckModel = false;
    soldierId!: string;

    chooseSoldierNum = 0;
    maxChooseSoldierNum = 0;

    setData(soldierId: string, soldierNum: number, isQuickChecked = false) {
        this.isQuickCheckModel = isQuickChecked;
        const soldierCfgData = XLSX.SOLDIER[soldierId];
        this.soldierId = soldierId;
        soldierNum = getNumFloor(soldierNum);
        this.soldierNameLab!.string = `${soldierCfgData.name}`;
        this.soldierNum!.string = `x ${soldierNum}`;
        this.chooseSoldierNum = isQuickChecked ? soldierNum : 0;
        this.maxChooseSoldierNum = soldierNum;
        this.soldierDispatchInput!.string = `${getNumFloor(this.chooseSoldierNum)}`;
        if (this.isQuickCheckModel) {
            this.soldierDispatchInput.node.active = false;
        } else {
            this.soldierDispatchInput.node.active = true;
        }
    }

    setQuickState(isQuickChecked: boolean) {
        this.isQuickCheckModel = isQuickChecked;
        if (this.isQuickCheckModel) {
            this.soldierDispatchInput.node.active = false;
            this.soldierDispatchInput!.string = `${getNumFloor(this.maxChooseSoldierNum)}`;
        } else {
            this.soldierDispatchInput.node.active = true;
        }
    }

    changeSoldierNum() {
        if (this.soldierDispatchInput!.string) {
            const inputNum = Number(this.soldierDispatchInput!.string);
            this.chooseSoldierNum = getNumFloor(
                inputNum > this.maxChooseSoldierNum ? this.maxChooseSoldierNum : inputNum
            );
        } else {
            this.chooseSoldierNum = 0;
        }
        this.soldierDispatchInput!.string = `${this.chooseSoldierNum}`;
        Engine.eventManager.emit(EVENT_NAME.CHOOSE_DISPATCH_SOLDIER_NUM, this.soldierId, this.chooseSoldierNum);
    }
}
